<?php

namespace app\api\controller;


use app\common\controller\Api;
use think\Db;

use Aws\S3\Exception\S3Exception;
use Aws\S3\S3Client;
use Aws\Sns\Exception\SnsException;
use Aws\Sns\SnsClient;



class Megoshop extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    //http://acciot.test/api/megoshop/sendsms?mobile=13564508883&msg=afasdf
    //SNS 发送短信
    //0912336153 -> +886912336153
    public function sendsms($mobile = "", $msg = "")
    {
        if (empty($mobile) || empty($msg)) {
            return 0;
        }

        echo "sendsms\n";

        $snsClient = new SnsClient([
            'region' => 'ap-northeast-1',
            'credentials' => [
                'key' => 'AKIA5QZ6FERNUUBXQ3XP',
                'secret' => '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',
            ],
            'version' => 'latest',
            'debug' => false,
        ]);
//        $snsClient = new SnsClient([
//            'region' => 'ap-northeast-1',
//            'credentials' => [
//                'key' => 'AKIAJRPDZKASP5ED4AEA',
//                'secret' => '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',
//            ],
//            'version' => 'latest',
//            'debug' => false,
//        ]);

        try {
            $args = [
                'Message' => $msg,           // REQUIRED
                'PhoneNumber' => $mobile,
            ];
            $snsClient->Publish($args);
            echo "OK\n";
            return 1;
        } catch (SnsException $e) {
            echo "SnsException\n".$e->getMessage();
        }

        echo "Error\n";
        return 1;

    }

    //http://acciot.test/api/megoshop/sendsmslist
    public function sendsmslist()
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限

        $sql = "SELECT * FROM ims_core_sendsms_log where issend = 0";
        $smslist = Db::connect('mysql://megoshop:Aitrip123@52.198.57.105:3306/megoshop#utf8')
            ->query($sql);

        $num = 0;
        foreach ($smslist as &$row) {
            if ($this->sendsms($row['mobile'], $row['content']) > 0) {
                $num++;
                $sql = "UPDATE ims_core_sendsms_log SET issend = 1 WHERE id = {$row['id']} ";
                Db::connect('mysql://megoshop:Aitrip123@52.198.57.105:3306/megoshop#utf8')->execute($sql);
            }
        }

        $this->success("发送成功！num=" . $num);

    }

}
